import { useState, useEffect } from "react"

const useFetch = (url) => {
    const [data, setData] = useState(null)
    const [isLoading, setIsLoading] = useState(true)
    const [error, setError] = useState(null)

    useEffect(() => {
        //run first render and every time dependencies list change

        //const abortCtl = new AbortController()  //abort when page is unmounted from dom which is unnecessary for now
        setTimeout(() => {
            //fetch(url, {signal: abortCtl.signal})   //associate fetch with abort signal
            fetch(url)   //associate fetch with abort signal
                .then(res => {
                    if (!res.ok) {
                        throw Error('Could not fetch the blog data')
                    }
                    return res.json()
                })
                .then(data => {
                    setData(data)
                    setIsLoading(false)
                    setError(null)
                })
                .catch(err => {
                    //console.log(err.message)
                    //if (err.name === "AbortError") {
                        //handle abort error
                        //console.log('fetch aborted')
                    //} else {
                        setError(err.message)
                        setIsLoading(false)
                        setData(null)
                    //}
                })
        }, 1000)
        //return () => abortCtl.abort()
    }, [url]);
    return {data, isLoading, error}
}

export default useFetch